﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace InhollandAir.App_Code
{
    public class Tools
    {
        public static string EncodePassword(string pass, string salt)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(pass);
            byte[] src = Convert.FromBase64String(salt);
            byte[] dst = new byte[src.Length + bytes.Length];
            Buffer.BlockCopy(src, 0, dst, 0, src.Length);
            Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
            HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
            byte[] hashing = algorithm.ComputeHash(dst);
            for (int i = 0; i < 5000; i++)
            {
                hashing = algorithm.ComputeHash(hashing);
            }
            byte[] inArray = algorithm.ComputeHash(dst);
            return Convert.ToBase64String(inArray);
        }

        public static string CreateSalt(int size = 8)
        {
            // Generate a cryptographic random number using the cryptographic 
            // service provider
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[size];
            rng.GetBytes(buff);
            // Return a Base64 string representation of the random number
            return Convert.ToBase64String(buff);
        }

        public static int CreateSessionId()
        {
            RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
            byte[] randomBytes = new byte[256 * sizeof(int)];
            random.GetBytes(randomBytes);
            int val = BitConverter.ToInt32(randomBytes,0);
            val &= 0x7fffffff;
            return val;
        }

        public static bool WaitAFewSeconds(int seconds)
        {
            int milliseconds = seconds * 1000;
            System.Threading.Thread.Sleep(milliseconds);
            return true;
        }
    }
}